import pickle
import json
import serverFiles
import variableUtils
import copy
import utils
from translations import t



virtual_dict = {}

def getFields(dataSourceName,tableId):
    #找到对应的数据表
    DataN = f"Data{tableId}"
    EventN = f"Event{tableId}"#特征标签
    table = {}
    for dt in serverFiles.dataSource['DataSourceArray']:
        if dt['Name'].lower() == dataSourceName.lower():#默认 local
            for d in dt['TableArray']:
                if d['Name'].lower() == DataN.lower():
                    # print('ok')
                    table = copy.deepcopy(d)
                else:
                    # print(d['Name'])
                    pass
    if table == {}:
        raise ValueError(f"在本地DataSource.json(根据runtime.ini路径)配置文件中找不到对应的数据源 {dataSourceName} 或者在该配置下未找到{DataN}")
    fields = []
     # 遍历TableArray下的 FieldArray
    table['FieldArray'].sort(key=lambda x: x['Order'])
    for field in table['FieldArray']:
        # 过滤RtCurveEnable为true的项
        varName = field.get('NameInFieldGroup')
        hasVar = variableUtils.hasVar(varName)

        try:
            Ext = field.pop('Ext','')
            ext_dict = json.loads(Ext)
            field['ext_dict'] = ext_dict
            if hasVar: 
                variableUtils.syncExtDict(varName, ext_dict)
        except:
            # print(f"""Invalid JSON string.{field['Name']}""")
            ext_dict = {}
        isVirtual = ext_dict.get('type','') in ['virtual','override']
        
        if field.get('HisTableEnable'):
            if hasVar:
                field['checked'] = True
                
                # 增加单位和精度
                unit = variableUtils.getUnit(varName,'')#单位
                pcs = variableUtils.getPCS(varName,1)#精度
                field['unit'] = unit
                field['pcs'] = pcs
                fields.append(field)
            elif isVirtual:
                variablePath = ext_dict.get('variablePath','')
                unit = variableUtils.getUnit(variablePath,'')#单位
                pcs = variableUtils.getPCS(variablePath,1)#精度
                pcs = ext_dict.get('pcs',pcs)
                unit = ext_dict.get('unit',unit)
                field['unit'] = unit
                field['pcs'] = pcs
                fields.append(field)
                virtual_dict[field['Name']] = field
     
    with open('table_virtual_dict.pkl', 'wb') as f:
        pickle.dump(virtual_dict, f)
    return fields

def getVirtualDict():
    global virtual_dict
    if len(virtual_dict) == 0:
        # 从文件中读取对象
        with open('table_virtual_dict.pkl', 'rb') as f:
            virtual_dict = pickle.load(f)
    return virtual_dict